package com.beiding.jsonanalyzer.flow;


import java.util.List;

/**
 * 分支节点
 */
public class BranchNode<T> {


    /**
     * 数据流
     * 算子产生
     */
    private DataFlow dataFlow;

    /**
     * 分支对象
     */
    private Branch<T> branch;


    public BranchNode(Branch<T> branch) {
        this.branch = branch;
        dataFlow = new DataFlow(this);
    }

    public void flush(Runnable runnable) {
        signDataEvent(new FlushEvent<>(runnable));
    }

    /**
     * 提交任务事件
     */
    public <W extends FlowEvent<T>> void signDataEvent(W event) {
        dataFlow.emit(event);
    }


    /**
     * 注册任务事件
     */
    public <W extends FlowEvent<T>> void onDataEvent(W type, EventListener<W> listener) {
        dataFlow.on(type.getClass(), listener);
    }

    /**
     * 移除任务事件
     *
     * @param type
     */
    public void removeDataListener(Class<?> type) {
        dataFlow.removeListener(type);
    }

    public <E> void addGlobalListener(Class<E> type, EventListener<E> listener) {
        branch.addListener(type, listener);
    }

    public <E> void removeGlobalListener(Class<E> type, EventListener<E> listener) {
        branch.removeListener(type, listener);
    }

    public void emitGlobal(Object globalEvent) {
        branch.emit(globalEvent);
    }

    public <E> List<EventListener<E>> getGlobalListeners(Class<E> type) {
        return branch.getListeners(type);
    }

    public void breakPressure(int size) {
        this.branch.breakPressure(size);
    }


    DataFlow getDataFlow() {
        return dataFlow;
    }

    public Branch<T> getBranch() {
        return branch;
    }

    public int getBreakPressureSize() {
        return branch.getBreakPressureSize();
    }
}
